package com.howso.cloud.uaa.service.impl;


import com.howso.cloud.feign.UserService;
import com.howso.cloud.oauth2.model.LoginAppUser;
import com.howso.cloud.uaa.service.HowsoUserDetailsService;
import com.howso.cloud.uaa.service.IHowsoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
public class UserDetailServiceImpl implements HowsoUserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private IHowsoUserService howsoUserService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        LoginAppUser loginAppUser = userService.findByUsername(username);
        if (loginAppUser.getId()==null) {
            loginAppUser = howsoUserService.findByUsername(username);
        }
        if (loginAppUser.getId()==null) {
            throw new InternalAuthenticationServiceException("用户名或密码错误");
        }
        return checkUser(loginAppUser);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String openId) {
        LoginAppUser loginAppUser = userService.findByOpenId(openId);
        return checkUser(loginAppUser);
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        LoginAppUser loginAppUser = userService.findByMobile(mobile);
        return checkUser(loginAppUser);
    }

    @Override
    public UserDetails loadUserByEmail(String email) {
        LoginAppUser loginAppUser = userService.findByEmail(email);
        return checkUser(loginAppUser);
    }
    @Override
    public UserDetails loadUserByIdCard(String idCard) {
        LoginAppUser loginAppUser = userService.findByIdCard(idCard);
        return checkUser(loginAppUser);
    }

    private LoginAppUser checkUser(LoginAppUser loginAppUser) {
        if (loginAppUser != null && !loginAppUser.isEnabled()) {
            throw new DisabledException("用户已作废");
        }
        return loginAppUser;
    }
}
